package com.github.xzb617.client.flow;

import com.github.xzb617.adm.service.FlowMetricService;
import com.github.xzb617.client.flow.dto.ClientFlowMetric;
import com.github.xzb617.utils.WebUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 流控指标收集端点
 * @author xzb617
 */
@RestController
@RequestMapping("/clients/flow")
public class FlowMetricEndpoint {

    // 日志
    private final static Logger LOGGER = LoggerFactory.getLogger(FlowMetricEndpoint.class);

    private final FlowMetricService flowMetricService;

    public FlowMetricEndpoint(FlowMetricService flowMetricService) {
        this.flowMetricService = flowMetricService;
    }

    /**
     * 收集一分钟的访问量度量指标
     * @param flowMetric 指标
     * @return 1: 表示成功接收, 0: 表示未成功接收
     */
    @PostMapping("/metric")
    public ResponseEntity<Integer> collect(ClientFlowMetric flowMetric, HttpServletRequest request) {
        if (flowMetric == null)
            return ResponseEntity.ok(0);
        LOGGER.info("Receive the reported flow metrics data from the client, details: {}", flowMetric.toString());
        String ip = WebUtil.getClientIpAddr(request);
        flowMetric.setInstanceId(ip + ":" + flowMetric.getInstanceId());
        this.flowMetricService.saveClientMetric(flowMetric);
        return ResponseEntity.ok(1);
    }

}
